<template>
  <div class="chart-container">
    <div class="sciChart" ref="sciChartRef" v-if="!empty"></div>
    <div class="empty-text flex justify-content-center align-items-center" v-if="empty">
      {{ text }}
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';
import {
  DataLabelState,
  ECoordinateMode,
  EHorizontalAnchorPoint,
  EStrokePaletteMode,
  FastLineRenderableSeries,
  EAnimationType,
  EVerticalTextPosition,
  IPointMetadata,
  IPointMarkerPaletteProvider,
  IRenderableSeries,
  LineSeriesDataLabelProvider,
  NumericAxis,
  NumberRange,
  parseColorToUIntArgb,
  SciChartSurface,
  SplineLineRenderableSeries,
  TextAnnotation,
  TPointMarkerArgb,
  TWebAssemblyChart,
  Thickness,
  TSciChart,
  XyDataSeries,
  XySeriesInfo,
  EllipsePointMarker,
  RolloverModifier,
  SciChartJsNavyTheme,
  MouseWheelZoomModifier,
  ZoomPanModifier,
  ZoomExtentsModifier,
  EAxisAlignment,
  VerticalSliceModifier,
} from 'scichart';

export interface SciChartOptions {
  debug?: boolean
  backgroundColor?: string
  xAxisOptions?: Partial<NumericAxis>
  yAxisOptions?: Partial<NumericAxis>
}

export interface SciChartSeries {
  data: { x: number[]; y: number[] }
  options?: {
    stroke?: string
    strokeThickness?: number
    seriesType?: 'line' | 'column' | 'mountain'
  }
}

const props = defineProps({
  options: SciChartOptions,
  series?: SciChartSeries[],
  text: {
    type: String,
    default: '暂无数据', // 请求接口的时候可改为加载中
  },
  empty: {
    type: Boolean,
    default: false,
  },
});

const sciChartRef = ref<HTMLElement | null>(null);
let chartInstance: ECharts | null = null;
let resizeObserver: ResizeObserver | null = null; // 提升到组件作用域

// 初始化图表
const initChart = async () => {
  if (!sciChartRef.value) return;

  // 销毁旧实例和观察者
  chartInstance.value = null;
  resizeObserver?.disconnect();

  try {
    const { sciChartSurface: surface } = await SciChartSurface.create(sciChartRef.value, {
      debug: options.debug || false,
      backgroundColor: options.backgroundColor || '#1C1C1E',
    });

    // 添加坐标轴
    surface.xAxes.add(
      new NumericAxis({
        axisAlignment: EAxisAlignment.Bottom,
        ...options.xAxisOptions,
      })
    );

    surface.yAxes.add(
      new NumericAxis({
        axisAlignment: EAxisAlignment.Left,
        ...options.yAxisOptions,
      })
    );

    chartInstance.value = surface;
  } catch (err) {
    console.error('SciChart initialization failed:', err);
  }
};

// 销毁图表
 const clearSeries = () => {
    if (chartInstance.value) {
      chartInstance.value.renderableSeries.clear()
    }
  }

// 清理资源
const destroy = () => {
  if (chartInstance.value) {
    chartInstance.value?.delete();
    chartInstance.value = null;
  }
};

// 监听系列变化
watch(() => props.series, (newSeries, oldSeries) => {
  if (!newSeries) return

  if (!oldSeries || newSeries.length !== oldSeries.length) {
    clearSeries()
    newSeries.forEach(series => addSeries(series))
  } else {
    // 这里可以添加更智能的更新逻辑
    clearSeries()
    newSeries.forEach(series => addSeries(series))
  }
}, { deep: true })

// 初始化完成后触发事件
watch(isInitialized, (initialized) => {
  if (initialized && sciChartSurface.value) {
    emit('initialized', sciChartSurface.value)

    // 添加初始系列
    if (props.series) {
      props.series.forEach(series => addSeries(series))
    }
  }
})

// 错误处理
watch(error, (err) => {
  if (err) emit('error', err)
})

// 组件卸载时清理
onUnmounted(() => {
    destroy()
})
</script>

<style lang="scss" scoped>
@import '~@/styles/common.scss';

.chart-container {
  width: 100%;
  height: 100%;

  .sci-chart {
    width: 100%;
    height: 100%;
  }

  .empty-text {
    width: 100%;
    height: 100%;
    font-weight: bold;
    font-size: 24px;
    letter-spacing: 2px;
  }
}
</style>
